package com.bountytask.config;

import com.bountytask.util.JwtUtil;
import com.bountytask.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //从 http 请求头中取出 token
        String token = request.getParameter("token");
        System.out.println("此处测试是否拿到了token：" + token);

        if (token == null) {
            throw new RuntimeException("无 token ，请重新登陆");
        }

        if (!redisUtils.hasKey(token)){
            throw new RuntimeException("token过期");
        }

        //验证 token
         JwtUtil.checkSign(token);

        //验证通过后， 这里测试取出JWT中存放的数据
        //获取 token 中的 userId
        long userId = (long) redisUtils.get(token);
        System.out.println("id : " + userId);

        //获取 token 中的其他数据
        String info = JwtUtil.getInfo(token);
        System.out.println(info);
        return true;
    }
}

